from PyQt5 import QtGui
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QTableWidget, QAbstractItemView, QHeaderView


class MyTableWidget(QTableWidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        # =================设置tableWidget样式=====================
        # 单击选择一行
        self.setSelectionBehavior(QAbstractItemView.SelectRows)
        # 设置只能选择一行，不能多行选中
        self.setSelectionMode(QAbstractItemView.SingleSelection)
        # 设置每行内容不可更改
        self.setEditTriggers(QAbstractItemView.NoEditTriggers)
        # 设置隔一行变一颜色，即：一灰一白
        self.setAlternatingRowColors(True)
        # 隐藏行号
        self.verticalHeader().hide()

        self.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

        self.horizontalHeader().setSectionsClickable(True)

        # 整行显示
        self.setSelectionBehavior(QAbstractItemView.SelectRows)

        # 隐藏行和列的表头
        # self.horizontalHeader().setVisible(False)
        # self.verticalHeader().setVisible(False)

        # 自适应调z整行和列的大小
        self.resizeColumnsToContents()
        self.resizeRowsToContents()

        # 隐藏表格线
        #self.setShowGrid(False)


    def keyPressEvent(self, e: QtGui.QKeyEvent) -> None:
        super(MyTableWidget, self).keyPressEvent(e)
        row = self.currentRow()
        col = self.currentColumn()
        if e.key() == Qt.Key_Enter or e.key() == Qt.Key_Return and 0 <= row < self.rowCount():
            self.cellDoubleClicked.emit(row, col)
